<template>
  <div id="homechart2">
    <div class="chart-box-graph" v-if="data && data.datas?.length > 0">
      <div class="chart-box">
        <div class="chart" ref="chart"></div>
        <!-- <div class="all-btn" @click="getList()">返回</div> -->
      </div>
    </div>
    <div class="no-data" v-else>
      <img src="@/assets/img/no-data.png" alt="" />
      <span>暂无内容</span>
    </div>
    <div class="graph-item-right" v-if="data && data.datas?.length > 0">
      <div>
        <div>
          <div class="item-txt">学习进度</div>
          <div class="item-num">{{ data.study }}</div>
        </div>
        <div class="pie-box">{{ data.study }}</div>
      </div>
      <div>
        <div>
          <div class="item-txt">掌握情况</div>
          <div class="item-num">{{ data.zhangwo }}</div>
        </div>
        <div class="pie-box">{{ data.zhangwo }}</div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";
import eventBus from "@/utils/eventBus";
export default {
  data() {
    return {
      classId: "",
      chart: null,
      // colors: [
      //   "#5470C6",
      //   "#91CC75",
      //   "#FAC858",
      //   "#EE6666",
      //   "#73C0DE",
      //   "#3BA272",
      //   "#FC8452",
      //   "#9A60B4",
      //   "#ea7ccc",
      // ],
      colors: ["#9ddcfb", "#9dc3fb", "#abece2", "#dee8fb", "#f4f8cc"],

      data: {
        datas: [],
        links: [],
        categories: [],
      },
      option: {
        // backgroundColor: new this.$echarts.graphic.RadialGradient(
        //   0.3,
        //   0.3,
        //   0.8,
        //   [
        //     {
        //       offset: 0,
        //       color: "#f7f8fa",
        //     },
        //     {
        //       offset: 1,
        //       color: "#cdd0d5",
        //     },
        //   ]
        // ),
        // title: {
        //   text: "三国演义中人名出现次数排名",
        //   subtext: "ZBH",
        //   top: "top",
        //   left: "center",
        // },
        tooltip: {
          trigger: "item", // 根据你的需求设置触发方式
          formatter: function (params) {
            // 判断是否是线条（edge）
            if (params.dataType === "edge") {
              return null; // 如果是线条，则不显示 tooltip
            }
            // 使用 params.marker 保留颜色小球
            return `${params.marker} ${params.name}: <span style="color:${params.color};font-weight:bold;">${params.value}%</span>`;
          },
        },
        animationDuration: 3000,
        animationEasingUpdate: "quinticInOut",
        series: [
          {
            type: "graph",
            layout: "force",
            zoom: 2.5,
            // layout: 'circular',
            force: {
              repulsion: 200,
              //两点间的距离
              // edgeLength: 5,
              //中心力
              // gravity: 0.1,
              //斥力系数
              // repulsion: 50,
              //
              // layoutAnimation: false,
              //减缓移动
              // friction: 0.6,
            },

            data: [],
            links: [],
            categories: [],
            emphasis: {
              focus: "adjacency",
            },
            // focusNodeAdjacency: true,
            roam: true,
            // label: {
            //     show: true,
            //     position: "top",
            // },
            label: {
              show: true, // 显示标签
              position: "inside", // 将标签位置设为节点内部
              formatter: "{b}", // 使用节点名称作为标签文本
              fontSize: 14, // 根据需要调整字体大小
              color: "#000", // 根据需要调整字体颜色
            },
            lineStyle: {
              // color: "source",
              color: "#c6d0d6",
              curveness: 0,
              type: "solid",
            },
            // itemStyle: {
            //     // borderColor: "#04f2a7",
            //     // borderWidth: 6,
            //     // shadowBlur: 20,
            //     // shadowColor: "#04f2a7",
            //     color: function(params){
            //       const colors = ["#ff5722", "#4caf50", "#2196f3", "#9c27b0"];
            //       console.log(params,3334);
            //       const color = colors[params.data.value % colors.length];
            //       console.log(color,555);
            //       return color;
            //     },
            // },
          },
        ],
      },

      //测试数据
    };
  },
  watch: {
    data: {
      handler(newVal) {
        // 当数据变化时，通知父组件数据状态
        this.$emit(
          "data-status",
          newVal && newVal.datas && newVal.datas.length > 0
        );
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.classId = JSON.parse(localStorage.getItem("classId"));
    // 移除立即初始化图表的代码，改为在数据加载成功后初始化
    this.getList();
    // 监听班级变更事件
    eventBus.on("classChanged", this.handleClassChanged);
  },
  beforeUnmount() {
    // 清理事件监听器
    eventBus.off("classChanged", this.handleClassChanged);
  },
  methods: {
    handleClassChanged(newClassId) {
      this.classId = newClassId;
      this.getList();
    },
    initChart() {
      // 确保 DOM 元素存在后再初始化
      this.$nextTick(() => {
        if (!this.$refs.chart) {
          console.error("Chart DOM element not found");
          return;
        }

        // 如果图表已经存在，先销毁
        if (this.myChart) {
          this.myChart.dispose();
        }

        this.chartDom = this.$refs.chart;
        this.myChart = this.$echarts.init(this.chartDom);
        this.myChart.setOption(this.option);
        this.myChart.hideLoading();

        // 清空之前的点击事件监听器
        this.myChart.off("click");

        // 添加节点点击事件
        this.myChart.on("click", (params) => {
          // 判断是否点击的是节点
          if (params.dataType === "node") {
            // 获取点击的节点数据
            const clickedNode = params.data;
            console.log(clickedNode, 222);
            //attachBookId,nodeId
            // this.getSubList(clickedNode.attachBookId, clickedNode.nodeId);
          }
        });
      });
    },
    initColors() {
      const data = this.option.series[0].data;
      const colors = this.colors;

      if (data && data.length > 0) {
        data.forEach((item, index) => {
          if (item && item.nodeLevel) {
            item.itemStyle = {
              color: colors[item.nodeLevel - 1] || colors[0],
            };
          }
        });
      }
    },
    initSymbolSize() {
      const data = this.option.series[0].data;
      const levels = [100, 50, 30, 20];

      if (data && data.length > 0) {
        data.forEach((item, index) => {
          // 直接设置，与 HomeChart2.vue 保持一致
          if (item && item.nodeLevel) {
            item.symbolSize = levels[item.nodeLevel - 1] || levels[0];
          }
        });
      }
    },
    initFontsize() {
      const data = this.option.series[0].data;

      if (data && data.length > 0) {
        const obj = data.find((item) => item.nodeLevel == 1);
        if (obj) {
          obj.label = {
            fontSize: 30,
          };
        }
      }
    },
    initOption() {
      const series = this.option.series[0];
      series.data = this.data.datas;
      series.links = this.data.links;
      const categories = this.data.datas?.map((item) => {
        return item.nodeLevel == 2;
      });
      series.categories = categories;

      this.initColors();
      this.initFontsize();
      this.initSymbolSize();
    },
    initChartGraph() {
      // 如果图表未初始化，先初始化
      if (!this.myChart) {
        this.initChart();
      }

      // 确保图表存在后再设置选项
      if (this.myChart) {
        this.myChart.setOption(this.option);
        this.myChart.hideLoading();
        // 清空之前的点击事件监听器
        this.myChart.off("click");
        // 添加节点点击事件
        this.myChart.on("click", (params) => {
          // 判断是否点击的是节点
          if (params.dataType === "node") {
            // 获取点击的节点数据
            const clickedNode = params.data;
            console.log(clickedNode, 222);
            //attachBookId,nodeId
            // this.getSubList(clickedNode.attachBookId, clickedNode.nodeId);
          }
        });
      }
    },

    getList() {
      let url = "";
      if (this.classId) {
        url = `/tes/graph/graph-relation-course?courseId=${this.courseId}&statistics=1&classId=${this.classId}`;
      } else {
        url = `/tes/graph/graph-relation-course?courseId=${this.courseId}&statistics=1`;
      }
      // const params = {
      //   bookInfoId: 1, // 使用 params 传递查询参数
      // };

      // 如果图表已存在，显示加载状态
      if (this.myChart) {
        this.myChart.showLoading({
          text: "正在加载数据...",
          color: "#4cbbff",
          maskColor: "rgba(255, 255, 255, 0.8)",
          zlevel: 0,
        });
      }

      this.$axios.get(url).then((response) => {
        const res = response;
        this.data = res.data || {};
        // 触发数据状态事件
        this.$emit(
          "data-status",
          this.data && this.data.datas && this.data.datas.length > 0
        );
        this.initOption();
        this.initChartGraph();
      });
    },
    getSubList(bookid, nodeId) {
      const url = "/dify/graph-relation-step";
      // 使用 params 传递查询参数
      const params = {
        bookId: bookid,
        nodeId: nodeId,
      };

      if (this.myChart) {
        this.myChart.showLoading({
          text: "正在加载数据...",
          color: "#4cbbff",
          maskColor: "rgba(255, 255, 255, 0.8)",
          zlevel: 0,
        });
      }

      this.$axios
        .get(url, {
          params, // 将参数传递给 `params` 属性
        })
        .then((response) => {
          const res = response;
          const isEmptyArray = (data) => data && data.length === 0;
          console.log(isEmptyArray(res.data), 333);
          if (isEmptyArray(res.data)) {
            if (this.myChart) {
              this.myChart.hideLoading();
            }
            this.$message.error(res.msg);
            return;
          }
          this.data = res.data;
          this.initOption();
          this.initChartGraph();
        })
        .finally(() => {
          if (this.myChart) {
            this.myChart.hideLoading();
          }
        });
    },
  },
};
</script>
<style lang="scss" scoped>
#homechart2 {
  position: relative;
  width: 100%;
  display: flex;
  .chart-box-graph {
    width: 100%;
    > div {
      position: relative;
      .chart {
        width: 100%;
        height: 660px;
        padding: 10px;
        box-sizing: border-box;
      }
      .all-btn {
        position: absolute;
        top: 10px;
        left: 10px;
      }
    }
  }
  .no-data {
    width: 100%;
    padding: 260px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font-size: 16px;
    color: #999;
    background-color: #f3f5fa;
  }
  .graph-item-right {
    width: 237px;
    position: absolute;
    top: 45px;
    right: 45px;
    // margin: 45px 45px 0 0;
    > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 237px;
      height: 103px;
      background: #ffffff;
      box-shadow: 5px 8px 27px 0px #b9caea;
      border-radius: 10px;
      padding: 0 23px 0;
      box-sizing: border-box;
      margin-bottom: 30px;
      .item-txt {
        font-weight: bold;
        font-size: 14px;
        color: #474747;
        margin-bottom: 8px;
      }
      .item-num {
        font-weight: bold;
        font-size: 25px;
        color: #2f7cdb;
      }
      .pie-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 74px;
        height: 74px;
        background: url("@/assets/img/home/pie.png") no-repeat 0 0;
        font-weight: bold;
        font-size: 14px;
        color: #ffffff;
      }
    }
  }
}
</style>